module PNEngine
  class Place < ActiveRecord::Base
    include Resource::InstanceMethods
    extend Resource::ClassMethods
    
    belongs_to :petrinet
    
    has_many :tokens, :dependent => :delete_all
    has_many :locators, :dependent => :delete_all
    has_many :arcs
    
    # Deletes all tokens with given case from place.
    def reset_tokens(c)
      self.tokens.find(:all, :conditions => ["case_id = ?", c.id]).collect{|t|t.destroy}
    end
    
    # Puts new token on place
    def push(token)
      self.tokens << token
    end
    
    # Consumes given token from place
    def pull(token)
      self.tokens.destroy(token.id)
    end
    
    private
    before_update :sanitize
    #strips place name
    def sanitize
      self.name = self.name.strip
    end
    
    before_create :label_place
    def label_place
      self.name = self.pid if self.name.blank?
    end

  end
end
